package com.ys.web.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ys.extend.utils.RandomNumUtils;
import com.ys.web.dao.CommonDao;
import com.ys.web.pojo.CompanyInfo;
import com.ys.web.pojo.SearchHotWordInfo;
import com.ys.web.service.CompanyService;
import com.ys.web.service.OptimizationStrategyService;
import com.ys.web.ws.service.ExceptionOneWeekIpService;
import com.ys.web.ws.service.ManageCompanyInfoService;

/**
 * 实现类
 * @author 谢政良
 *
 */
@Service("OptimizationStrategyService")
@Transactional
public class OptimizationStrategyServiceImpl implements OptimizationStrategyService {
	
	@Autowired
	private CommonDao commonDao;
	//数据源
	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private CompanyService companyService;

	@Resource
	private ManageCompanyInfoService manageCompanyInfoService;

	@Resource
	private ExceptionOneWeekIpService exceptionOneWeekIpService;
	//哪家好、好不好、什么好、好吗、多少钱、价格，哪里有、哪些、靠谱、公司、厂家、在哪里、**到**（含地域）、多少、价格表、价目表、品牌、排名、排行、性价比、便宜、安装 、系统、定制、批发、怎么样、如何、有用吗、好用吗
	private static String[] givenWord = new String[]{"哪家好", "好不好", "什么好", "好吗", "多少钱", "价格", "哪里有", "哪些", "靠谱",
			"公司", "厂家", "在哪里", "**到**（含地域）","多少", "价格表", "价目表", "品牌", "排名", "排行", "性价比", "便宜", "安装 ", "系统", "定制", "批发", "怎么样", "如何",
			"有用吗", "好用吗"};
	/**
	 * 二、	点击低（点击量、点击率）
	 */
	public String lowClick(int companyId, String industryId) {
		List<Integer> list = new ArrayList<Integer>();
		Random r = new Random();
		while(list.size()<3){
			int num = r.nextInt(5)+1;
			if(!list.contains(num)){
			   list.add(num);
			  } 
		}
		StringBuffer result = new StringBuffer();
		for (Integer ranNum : list) {
			if(ranNum==1){
				result.append(this.lowClickFor1()).append("</br>");
			}
			if(ranNum==2){
				result.append(this.lowClickFor2(companyId)).append("</br>");
			}
			if(ranNum==3){
				result.append(this.lowClickFor3()).append("</br>");
			}
			if(ranNum==4){
				result.append(this.lowClickFor4()).append("</br>");
			}
			if(ranNum==5){
				result.append(this.lowClickFor5(companyId)).append("</br>");
			}
		}
	return result.toString();
	}
	
	/**
	 * 三、转化量低：
	 */
	public String lowConversionRate(int companyId, String industryId,String industryName) {
		List<Integer> list = new ArrayList<Integer>();
		Random r = new Random();
		while(list.size()<3){
			int num = r.nextInt(6)+1;
			if(!list.contains(num)){
			   list.add(num);
			  } 
		}
		StringBuffer result = new StringBuffer();
		for (Integer ranNum : list) {
			if(ranNum==1){
				result.append(this.lowConversionRateFor1()).append("</br>");
			}
			if(ranNum==2){
				result.append(this.lowConversionRateFor2(companyId)).append("</br>");
			}
			if(ranNum==3){
				result.append(this.lowConversionRateFor3()).append("</br>");
			}
			if(ranNum==4){
				result.append(this.lowConversionRateFor4()).append("</br>");
			}
			if(ranNum==5){
				result.append(this.lowConversionRateFor5(companyId)).append("</br>");
			}if(ranNum==6){
				result.append(this.stratege36(industryId, companyId));
			}
		}
		if("节能环保".equals(industryName)){
			result.append(this.stratege37()).append("</br>");
		}if("物流".equals(industryName)){
			result.append(this.stratege38()).append("</br>");
		}if("租车".equals(industryName)){
			result.append(this.strateget39()).append("</br>");
		}
	return result.toString();
	}

	/*二、点击低（点击量、点击率）
	 * 1、拓宽关键词的匹配模式，（将“精确模式”调整为“精确包含”； “精确包含”调整为“同义包含”；“同义包含”调整为“核心包含”；“核心包含”调整为“广泛"）[随机两种匹配模式]
	 */
	public String lowClickFor1(){
		List<Integer> list = new ArrayList<Integer>();
		Random r = new Random();
		while(list.size()<2){
			int num = r.nextInt(4);
			if(!list.contains(num)){
			   list.add(num);
			  } 
			}
		 String MatchingMode[] = new String[]{
				 "将“精确模式”调整为“精确包含”",
				 "将“精确包含”调整为“同义包含”",
				 "将”同义包含”调整为“核心包含”",
		 		 "将“核心包含”调整为“广泛"};
		 StringBuffer result = new StringBuffer();
		for (Integer in : list) {
			result.append(MatchingMode[in]).append("；");
		}
		result.deleteCharAt(result.length()-1).append("。");
		return result.toString();
	}
	
	/*二、点击低（点击量、点击率）
	 * 查看重点词[从上传该客户的搜索词报告里提取转化率最高的10个关键词]的排名，将这部分重点词的价格出价提升20%，观察排名情况
	 */
	public String lowClickFor2(int companyId){
		 StringBuffer result = new StringBuffer();
		 String mainBusiness = this.getMajorBusiness(companyId);
		 StringBuffer sql = new StringBuffer();
		 sql.append("SELECT SUM(totalnumber_consult)/SUM(number_click) AS 'conversionRate' ,SUM(number_click) AS 'numberClick',")
		 .append("SUM(totalnumber_consult) AS 'totalnumberConsult', keyword_search AS 'keyWord'")
		 .append(" FROM origin_baidu where 1=1")
		 .append(" AND company_id='").append(companyId).append("'").append(mainBusiness)
		 .append(" GROUP BY keyword_search")
		 .append(" ORDER BY SUM(totalnumber_consult) DESC LIMIT 10");
		 List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(String.valueOf(sql));
		 if(queryForList.size()>0){
			 result.append("查看重点词的排名，将这部分重点词的价格出价提升20%，观察排名情况。重点词有：");
			 result.append("<br/>");
			 for (Map<String, Object> map : queryForList) {
				 String keyword = (String) map.get("keyWord");
				 result.append("&nbsp;&nbsp;&nbsp;&nbsp;");
				 result.append(keyword).append("<br/>");
			 }
			 result.delete(result.length()-5, result.length());
			 return result.toString();
		 }else{
			 return result.append("</br>").toString();
		 }
		 
	}
	
	/*
	 * 二、点击低（点击量、点击率）
	 * 3、搜索下拉框查看搜索热词，适当添加关键词数量（10-50）[数字在范围内随机]，
	 */
	public String lowClickFor3(){  
		int temp = (int) (10+Math.random()*40);
		String result="搜索下拉框查看搜索热词，适当添加关键词数量"+temp+"个。";
		return result;
	}
	
	/*
	 * 二、点击低（点击量、点击率）
	 * 4、创意通顺、通配符符合百度规则的创意，但创意形式不够多样，建议增加（闪头、图文信息、凤巢头条）等创意模式
	 */
	public String lowClickFor4(){
		return "创意通顺、通配符符合百度规则的创意，但创意形式不够多样，建议增加（闪投、图文信息、凤巢头条）等创意模式。";
	}
	
	/*
	 * 二、点击低（点击量、点击率）
	 * 5、将一个月内展现量高于10次但没点击的词[从上传的搜索词报告里提取符合条件的10个关键词]进行匹配调整或者提高出价，让这部分的关键词进行消费
	 */
	public String lowClickFor5(int companyId){
		StringBuffer result = new StringBuffer();
		String mainBusiness = this.getMajorBusiness(companyId);
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT keyword_search AS 'keyWord',SUM(number_exhibit) AS 'numberExhibit',")
		.append(" SUM(number_click) AS 'number_click' FROM origin_baidu")
		.append(" WHERE number_exhibit>10")
		.append(" AND number_click=0")
		.append(" AND company_id =").append(companyId).append(mainBusiness)
		.append(" AND DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(promotion_date)")
		.append("GROUP BY keyword_search LIMIT 10");
		List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(String.valueOf(sql));
		if(queryForList.size()>0){
			result.append("<br/>");
			result.append( "一个月内展现量高于10次但没点击的词进行匹配调整或者提高出价，让这部分的关键词进行消费。展现量高于10次但没点击的词：");
			for (Map<String, Object> map : queryForList) {
				String keyword = (String) map.get("keyWord");
				 result.append("&nbsp;&nbsp;&nbsp;&nbsp;");
				result.append(keyword).append("<br/>");
			}
			result.delete(result.length()-5, result.length());
			return result.toString();
		}else{
			return result.append("</br>").toString();
		}
	}
	
	/*
	 * 三、转化量低：
	 *1 、查看搜索词报告，看消费词（搜索词）是否跟关键词相关，如不相关则添加否词、调整关键词匹配模式
	 */
	private String lowConversionRateFor1() {
		return "查看搜索词报告，看消费词（搜索词）是否跟关键词相关，如不相关则添加否词、调整关键词匹配模式。";
	}
	
	/*
	 * 三、转化量低：
	 * 2、关键词[KAD系统行业里提取有消费转化最低（无转化）的10个关键词]、创意内容与落地页介绍不匹配，修改落地页URL
	 */
	private String lowConversionRateFor2(int companyId) {
		StringBuffer sql = new StringBuffer();
		String mainBusiness = this.getMajorBusiness(companyId);
		sql.append("SELECT keyword_search AS 'keyWord' FROM origin_baidu WHERE")
		.append(" company_id=").append(companyId).append(mainBusiness)
		.append(" AND totalnumber_consult=0")
		.append(" AND consume>0  GROUP BY keyword_search")
		.append(" ORDER BY SUM(totalnumber_consult) ASC LIMIT 10");
		List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(String.valueOf(sql));
		StringBuffer result = new StringBuffer();
		if(queryForList.size()>0){
			result.append("关键词、创意内容与落地页介绍不匹配，修改落地页URL。这部分关键词有：");
			result.append("<br/>");
			for (Map<String, Object> map : queryForList) {
				String keyword = (String) map.get("keyWord");
				 result.append("&nbsp;&nbsp;&nbsp;&nbsp;");
				result.append(keyword).append("<br/>");
			}
			result.delete(result.length()-5, result.length());
			return result.toString();
		}else{
			return result.append("</br>").toString();
		}
	}
	
	/*
	 * 三、转化量低：
	 * 3、落地页打开速度超过5秒，提高网站打开速度
	 */
	private String lowConversionRateFor3() {
		return "落地页打开速度超过5秒，提高网站打开速度。";
	}
	
	/*
	 * 三、转化量低：
	 * 4、最近3日访问时长（10秒-30秒），[范围内随机一个数值（最好真实数据）]页面美观度不够
	 */
	private String lowConversionRateFor4() {
		StringBuffer result = new StringBuffer();
		int temp = (int) (10+Math.random()*20);
		result.append("最近3日访问时长").append(temp).append("秒，访问时长过短，页面吸引力不够，建议对页面进行改版。");
		return result.toString();
	}
	
	/*
	 * 三、转化量低：
	 * 5、沟通工具在投放时间内存在没及时登陆管理的情况，请确保广告投放时间段沟通工具在线。
	 */
	private String lowConversionRateFor5(int companyId) {
		return "沟通工具在投放时间内存在没及时登陆管理的情况，请确保广告投放时间段沟通工具在线。";
	}

	/**
	 * 一、展现量低
	 * 1、拓宽关键词的匹配模式
	 */
	public String stratege11() {
		// TODO Auto-generated method stub
		int[] num = RandomNumUtils.getRandoms(1, 4, 2);
		String[] str = {"“精确模式”调整为“精确包含”","“精确包含”调整为“同义包含”","“同义包含”调整为“核心包含”","“核心包含”调整为“广泛”"};
    	StringBuffer sb = new StringBuffer();
    	sb.append("拓宽关键词的匹配模式，");
    	for(int j = 0 ; j < num.length ; j++){
    		sb.append(str[j]);
    		if(j!=num.length-1){
    			sb.append(", ");
    		}else{
    			sb.append(" 。");
    		}
    	}
    	return sb.toString();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> stratege12(String IndID) {
		// TODO Auto-generated method stub
		String sql = " select * from SearchHotWord where industryId = '"+IndID+"'";
		return (List<T>) jdbcTemplate.queryForList(sql);
	}

	/**
	 * 一、展现量低
	 * 2.搜索下拉框查看搜索热词
	 */
	@Override
	public String getSearchHotWordInfo(String IndID) {
//		SearchHotWordInfo searchHotWordInfo = null;
		StringBuffer sb = new StringBuffer();
		int num[] = RandomNumUtils.getRandoms(10, 50, 1);
//		
//		List<SearchHotWordInfo> list = new ArrayList<>();
//		List<Map<String,Object>> s = stratege12(IndID);
//		if(s!=null&&!s.isEmpty()){
//			for(int i = 0 ; i < s.size() ; i++){
//			searchHotWordInfo = new SearchHotWordInfo();
//			searchHotWordInfo.setIndustryId((String)s.get(i).get("industryId"));
//			searchHotWordInfo.setIndustryName((String)s.get(i).get("industryName"));
//			searchHotWordInfo.setIndustryHotWord((String)s.get(i).get("industryHotWord"));
//			list.add(searchHotWordInfo);
//			}
//		}
//		if(list!=null&&!list.isEmpty()){
		List<Integer> list = new ArrayList<Integer>();
		Random r = new Random();
		int temp = (int) (3+Math.random()*3);
		while(list.size()<temp){
			int random = r.nextInt(givenWord.length)+1;
			if(!list.contains(random)){
			   list.add(random);
			  } 
		}
		sb.append("搜索下拉框查看搜索热词，适当添加关键词数量"+num[0]+"个,多加一些长尾词（价格词、疑问词、公司词），可在主营业务词加入一些特定的词性，譬如，加入以下词：");
		for (Integer i : list) {
			sb.append(givenWord[i-1]).append("、");
		}
		sb.deleteCharAt(sb.length()-1).append("。");
//			for(SearchHotWordInfo ss : list){
//				sb.append(ss.getIndustryHotWord());
//				sb.append("\n");
//			}
//		}else{
//			sb.append("搜索下拉框查看搜索热词，适当添加关键词数量"+num[0]+"个。");
//		}
		return sb.toString();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> stratege13(Integer comID) {
		// TODO Auto-generated method stub
		String mainBusiness = this.getMajorBusiness(comID);
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT keyword_search,SUM(consume) AS 'consume' FROM origin_baidu WHERE	origin_baidu.company_id = "+comID).append(mainBusiness);
		sb.append(" and promotion_date between '").append(getBeforeSimpleDate()).append("' and '").append(getNowSimpleDate()).append("'");
		
		sb.append(" and keyword_search not in('百度外链','直接访问','360外链') GROUP BY(origin_baidu.`keyword_search`) order by sum(consume) asc LIMIT 5 ");
		
		return (List<T>) jdbcTemplate.queryForList(sb.toString());
	}

	public static String getBeforeSimpleDate() {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		Calendar ca_before = Calendar.getInstance();
		ca_before.set(Calendar.DATE, ca_before.get(Calendar.DATE) - 8);
		return sd.format(ca_before.getTime());
	}
	

	public static String getNowSimpleDate() {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		Calendar ca_before = Calendar.getInstance();
		ca_before.set(Calendar.DATE, ca_before.get(Calendar.DATE) - 1);
		return sd.format(ca_before.getTime());
	}
	
	/**
	 * 一、展现量低
	 * 3.最近一周，消费最低的5个关键词。
	 */
	public String getLowConsume(Integer comID) {
		// TODO Auto-generated method stub
		List<Map<String,Object>> lm = stratege13(comID);
		StringBuffer sb = new StringBuffer();
		
		if(lm!=null&&!lm.isEmpty()){
			sb.append("提高关键词");
			sb.append("出价。关键词：").append("<br>");
			for(int i = 0 ; i< lm.size();i++){
				sb.append("&nbsp;&nbsp;&nbsp;&nbsp;");
				sb.append(lm.get(i).get("keyword_search"));
				if(i!=lm.size()-1){
					sb.append("<br>");
				}else{
					sb.append("<br>");
				}
			}
			return sb.toString();
		}else{
			return "";
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> stratege14(Integer comID) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		String mainBusiness = this.getMajorBusiness(comID);
		sb.append("SELECT keyword_search FROM origin_baidu WHERE company_id = "+comID).append(mainBusiness);
		sb.append(" and promotion_date between '").append(getBeforeSimpleDate()).append("' and '").append(getNowSimpleDate()).append("'");
		sb.append(" and keyword_search not in('百度外链','直接访问','360外链') and number_exhibit = 0 GROUP BY(`keyword_search`) LIMIT 10 ");
		return (List<T>) jdbcTemplate.queryForList(sb.toString());
	}

	/**
	 * 一、展现量低
	 * 4.一周内没有展现的关键词
	 */
	public String getNoneKeyWord(Integer comID) {
		// TODO Auto-generated method stub
		List<Map<String,Object>> lm = stratege14(comID);
		StringBuffer sb = new StringBuffer();
		if(lm!=null&&!lm.isEmpty()){
			sb.append("将一周内没有展现的关键词");
			sb.append("进行匹配调整或者提高出价，让这部分的关键词进行消费。一周内没有展现的关键词：").append("<br>");
			for(int i = 0 ; i< lm.size();i++){
				sb.append("&nbsp;&nbsp;&nbsp;&nbsp;");
				sb.append(lm.get(i).get("keyword_search"));
				if(i!=lm.size()-1){
					sb.append("<br>");
				}else{
					sb.append("<br>");
				}
			}
			return sb.toString();
		}else{
			return "";
		}
	}

	/**
	 * 三、转化量低
	 * 7.节能环保行业
	 */
	@Override
	public String stratege37() {
		// TODO Auto-generated method stub
		return "节能环保行业无效点击比较多，大多数是个人去百度查去甲醛的小窍门，早上点击消费多但基本无转化，建议早上不投放或者是降低时段系数，下午晚上（16：00-21：00）转化会比较高。";
	}

	/**
	 * 三、转化量低
	 * 8.物流行业
	 */
	@Override
	public String stratege38() {
		// TODO Auto-generated method stub
		return "物流行业一般投放时间段为9:00-17:00，上午咨询较多，可着重查看上午的转化情况 。";
	}

	/**
	 * 三、转化量低
	 * 9.租车行业
	 */
	@Override
	public String strateget39() {
		// TODO Auto-generated method stub
		return "租车行业PC端的成交相对会比较高，加大PC端的投放力度 。";
	}

	/**
	 * 三、转化量低
	 * 6.潜在核心转化词 尚未被挖掘，可通过行业热搜核心转化词及长尾词 进行拓词
	 * 从KAD系统里按行业提取转化词最高的1-10个关键词
	 */
	public String stratege36(String IndID,Integer comID) {
		// TODO Auto-generated method stub
		String mainBusiness = this.getMajorBusiness(comID);
		StringBuffer getstr = new StringBuffer();
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT keyword_search,SUM(number_click) AS 'Totalclick',SUM(totalnumber_consult) AS 'Totalconsult' FROM origin_baidu where 1=1");
		//sb.append(" and promotion_date between '").append(getBeforeSimpleDate()).append("' and '").append(getNowSimpleDate()).append("'");
		sb.append(" and keyword_search not in('百度外链','直接访问','360外链')");
		sb.append(" and company_id = "+comID).append(mainBusiness);
		sb.append(" GROUP BY(keyword_search) ORDER BY (SUM(totalnumber_consult)/SUM(number_click)) desc limit 10");
		List<Map<String,Object>> lm = jdbcTemplate.queryForList(sb.toString());//找转化率高的关键词
//		List<Map<String,Object>> lm1 = stratege12(IndID);//找长尾词
		if(lm!=null&&!lm.isEmpty()){
			getstr.append("潜在核心转化词");
			getstr.append("尚未被挖掘，可通过行业热搜核心转化词及长尾词（价格词、疑问词、公司词）进行拓词。");
			getstr.append("潜在核心转化词有：").append("<br>");
			for(int i=0 ; i< lm.size();i++){
				getstr.append("&nbsp;&nbsp;&nbsp;&nbsp;");
				getstr.append(lm.get(i).get("keyword_search"));
				if(i!=lm.size()-1){
					getstr.append("<br>");
				}
			}
//			if(lm1!=null&&!lm1.isEmpty()){
//				getstr.append("<br>");
//				getstr.append("长尾词：").append("<br>");
//				SearchHotWordInfo searchHotWordInfo = null;
//				List<SearchHotWordInfo> list = new ArrayList<>();
//				for(int ii = 0 ; ii < lm1.size() ; ii++){
//					searchHotWordInfo = new SearchHotWordInfo();
//					searchHotWordInfo.setIndustryId((String)lm1.get(ii).get("industryId"));
//					searchHotWordInfo.setIndustryName((String)lm1.get(ii).get("industryName"));
//					searchHotWordInfo.setIndustryHotWord((String)lm1.get(ii).get("industryHotWord"));
//					list.add(searchHotWordInfo);
//					}
//				if(list!=null&&!list.isEmpty()){
//					for(SearchHotWordInfo ss : list){
//						getstr.append("&nbsp;&nbsp;&nbsp;&nbsp;");
//						getstr.append(ss.getIndustryHotWord()).append("。");
//					}
//				}
//			}
			getstr.append("</br>");
			return getstr.toString();
		}else{
			return "";
		}
	}

	@Override
	public String getFirstMethod(String IndID, Integer comID) {
		// TODO Auto-generated method stub
		int num[] = RandomNumUtils.getRandoms(1, 4, 3);
		StringBuffer sb = new StringBuffer();
		for(int n : num){
			switch (n) {
			case 1:
				sb.append(stratege11());
				break;
			case 2:
				sb.append(getSearchHotWordInfo(IndID));
				break;
			case 3:
				sb.append(getLowConsume(comID));
				break;
			case 4:
				sb.append(getNoneKeyWord(comID));
				break;
			}
			sb.append("</br>");
		}
		String str = sb.toString();
		if(str!=null&&str.length()!=0){
			return str;
		}else{
			return "";
		}
	}
	
	// 四、广告在线时间短
		public String shortOnlineAdvertisingTime(Integer companyId, String industryId, String industryName) {

			int[] functionNum;
			// 判断该行业是否要添加第7条
			
				functionNum = this.randomCommon(1, 7, 3);
			
			String str = "";
			for (int num : functionNum) {
				switch (num) {
				case 1:
					str += Advertisement01(companyId, industryId);
					break;
				case 2:
					str += Advertisement02(companyId, industryId);
					break;
				case 3:
					str += Advertisement03(companyId, industryId, industryName);
					break;
				case 4:
					str += Advertisement04(companyId, industryId);
					break;
				case 5:
					str += Advertisement05(companyId, industryId);
					break;
				case 6:
					str += Advertisement06(companyId, industryId);
					break;
				case 7:
					str += Advertisement07(companyId, industryId,industryName);
					break;
				}
			}

			
			return str;

		}

		// 产生随机数组
		public int[] randomCommon(int min, int max, int n) {
			if (n > (max - min + 1) || max < min) {
				return null;
			}
			int[] result = new int[n];
			int count = 0;
			while (count < n) {
				int num = (int) (Math.random() * (max - min)) + min;
				boolean flag = true;
				for (int j = 0; j < n; j++) {
					if (num == result[j]) {
						flag = false;
						break;
					}
				}
				if (flag) {
					result[count] = num;
					count++;
				}
			}
			return result;
		}

		public String Advertisement01(Integer companyId, String industryId) {

			StringBuffer str = new StringBuffer();
			str.append("查看搜索词报告，看消费词（搜索词）是否跟关键词相关，如不相关则添加否词、调整关键词匹配模式，");
			int[] functionNum = this.randomCommon(1, 4, 2);
			// （将“精确包含”调整为“精确模式”； “同义包含”调整为“精确包含”；“核心包含”调整为“同义包含”；“广泛”调整为“核心包含"）
			for (int num : functionNum) {
				switch (num) {
				case 1:
					str.append("将“精确包含”调整为“精确模式”，");
					break;
				case 2:
					str.append(" “同义包含”调整为“精确包含”，");
					break;
				case 3:
					str.append(" “核心包含”调整为“同义包含”，");
					break;
				case 4:
					str.append(" “广泛”调整为“核心包含”，");
					break;
				}
			}
			str.deleteCharAt(str.length() - 1);
			str.append("。");
			str.append("</br>");

			return str.toString();

		}

		// 观察核心消费词 的排名，将这几个关键词的价格减低30%观察结果。提取5个消费最高的关键词
		public String Advertisement02(Integer companyId, String industryId) {
			StringBuffer str = new StringBuffer();
			String mainBusiness = this.getMajorBusiness(companyId);
//			List<CompanyInfo> companyList = companyService.getCompanyByIndustry(industryId);
//			int length = companyList.size();
//			if (companyList.get(0).getId() == 0) {
//				return null;
//			} else {

//				StringBuffer companyIdsSql = new StringBuffer();
//				for (int i = 0; i < length; i++) {
//					Integer id = companyList.get(i).getId();
//					companyIdsSql = companyIdsSql.append("'").append(id).append("'").append(",");
//				}
//				companyIdsSql.deleteCharAt(companyIdsSql.length() - 1);// 多出来的逗号

				StringBuffer sql = new StringBuffer();

				sql.append("select keyword_search,sum(consume) as 'consume' from origin_baidu")
						.append(" where company_id =").append(companyId).append(mainBusiness)
						.append(" AND totalnumber_consult=0")
						.append(" AND keyword_search not in('百度外链','直接访问','360外链')").append("group by keyword_search")
						.append(" order by consume desc limit 10");
				
				List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(String.valueOf(sql));
				if (!queryForList.isEmpty()) {

					str.append("观察核心消费词 的排名，将这几个关键词的价格减低30%观察结果。消费最高的关键词有：<br/>");

					for (Map<String, Object> map : queryForList) {

						str.append("&nbsp;&nbsp;&nbsp;&nbsp;").append(map.get("keyword_search") ).append("<br/>");

					}
					str.delete(str.length() - 5,str.length());
				

//				}
				str.append("</br>");
				return str.toString();
			}else{
				return "";
			}

		}

		/*
		 * 3、(时段端) 为广告投放高峰期，关键词点击价格高，竞争大。避开高峰期进行广告投放，非高峰期可以着重调排名。
		 * 搬家、清洁、回收：9：00-11：00，12：00-14：00 租车、节能环保：9：00-12：00 其它行业：9：00-10：00
		 */
		public String Advertisement03(Integer companyId, String industryId, String industryName) {
			String str;
			if (industryName.equals("搬家") || industryName.equals("清洁") || industryName.equals("回收")) {

				str = "9：00-11：00，12：00-14：00";
			} else if (industryName.equals("租车") || industryName.equals("节能环保")) {
				str = "9：00-12：00";
			} else {
				str = "9：00-10：00";
			}
			str += "为该行业广告投放高峰期，关键词点击价格高，竞争大。尽量减少此高峰时间段的投放力度，非高峰期可以着重调排名。";
			str+="</br>";
			return str;

		}

		public String Advertisement04(Integer companyId, String industryId) {
			StringBuffer str = new StringBuffer();
			str.append("降低关键词的匹配模式宽度，");
			int[] functionNum = this.randomCommon(1, 4, 2);
			// （将“精确包含”调整为“精确模式”； “同义包含”调整为“精确包含”；“核心包含”调整为“同义包含”；“广泛”调整为“核心包含"）
			for (int num : functionNum) {
				switch (num) {
				case 1:
					str.append("将“精确包含”调整为“精确模式”，");
					break;
				case 2:
					str.append(" “同义包含”调整为“精确包含”，");
					break;
				case 3:
					str.append(" “核心包含”调整为“同义包含”，");
					break;
				case 4:
					str.append(" “广泛”调整为“核心包含”，");
					break;
				}
			}
			str.deleteCharAt(str.length() - 1);
			str.append("。");
			str.append("</br>");
			return str.toString();
		
		}

		public String Advertisement05(Integer companyId, String industryId) {
			StringBuffer str = new StringBuffer();
			str.append("存在恶意点击消费的情况，检查百度商盾的恶意点击屏蔽规则是否设置合理，查看访问IP，手动屏蔽恶意点击。");
			String userId = manageCompanyInfoService.getUserIdByCompanyId(companyId);
			SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd");
			Date d = new Date();

			String yesterday = sdf.format(new Date(d.getTime() - 1 * 24 * 60 * 60 * 1000));
			String oneWeekAgo = sdf.format(new Date(d.getTime() - 7 * 24 * 60 * 60 * 1000));
			List<String> ipList = new ArrayList(); 
			ipList = exceptionOneWeekIpService.getIpData(userId, yesterday, oneWeekAgo);
			if (ipList!=null) {//一周内有访问
				str.append("一周内访问的异常IP有：<br/>");
				for (String ip : ipList) {
					str.append("&nbsp;&nbsp;&nbsp;&nbsp;").append(ip).append("<br/>");
				}
				str.delete(str.length()-5,str.length());
				str.append("</br>");
				return str.toString();

			} else {//一周内无访问
				return "";
			}
			
		}

		public String Advertisement06(Integer companyId, String industryId) {
			String str = "检测到此账户的关键词出价变动异常，请检查账户排名自动倾向功能是否关闭。";
			str+="</br>";
			return str;
		}

		public String Advertisement07(Integer companyId, String industryId,String industryName) {
			if(industryName.equals("物流")){
				String str = "行业流量大，关键词建议设较精准的地域词，比如：xxx地方到或至xxx地方物流公司之类的词。 ";
				str+="</br>";
				return str;
			}else{
				return "";
			}
			
		}

		@Override
		public boolean isExist(int companyId) {
			String sql = "SELECT id FROM optimization_trategy WHERE company_id ="+companyId+" AND TO_DAYS(show_date) = TO_DAYS(NOW());";
			 List<Map<String, Object>> list = jdbcTemplate.queryForList(String.valueOf(sql));
			 if(list!=null&&list.size()!=0){
				 return true;
			 }else{
				 return false;
			 }
		}

		@Override
		public String getOptimizationTrategy(int companyId) {
			String sql ="SELECT optimization FROM optimization_trategy WHERE company_id ="+companyId;
			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
			if(list!=null&&list.size()>0){
				return list.get(0).get("optimization").toString();
			}else
				return null;
		}

		@Override
		public boolean saveOptimizationTrategy(int companyId, String optimizationTrategy) {
			StringBuffer sql = new StringBuffer();
			if(this.hasCompanyId(companyId)){
				sql.append("UPDATE optimization_trategy SET optimization='")
				.append(optimizationTrategy)
				.append("',show_date=NOW() WHERE company_id =")
				.append(companyId);
			}else{
				sql.append("INSERT INTO optimization_trategy(company_id,show_date,optimization) VALUE(")
				.append(companyId).append(",")
				.append("NOW()").append(",").append("'")
				.append(optimizationTrategy).append("')");
			}
			int update = jdbcTemplate.update(sql.toString());
			if(update!=0){
				return true;
			}else
			return false;
		}
		
		public boolean hasCompanyId(int companyId){
			String sql = "SELECT id FROM optimization_trategy WHERE company_id ="+companyId;
			 List<Map<String, Object>> list = jdbcTemplate.queryForList(String.valueOf(sql));
			 if(list!=null&&list.size()!=0){
				 return true;
			 }else{
				 return false;
			 }
		}
		
		
		/*
		 * 定量规则第一条
		 * 
		 * 1、将一个月内展现量高于10次但没点击的词[从上传的搜索词报告里提取符合条件的10个关键词]进行匹配调整
		 * （将“精确模式”调整为“精确包含”； “精确包含”调整为“同义包含”；“同义包含”调整为“核心包含”；“核心包含”调整为“广泛"）
		 * [随机两种匹配模式]或者将价格提成20%-30%，让这部分的关键词进行消费
		 */
		public String variableRule1(int companyId){
			String mainBusiness = this.getMajorBusiness(companyId);
			StringBuffer result = new StringBuffer();
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT keyword_search AS 'keyWord',SUM(number_exhibit) AS 'numberExhibit',")
			.append(" SUM(number_click) AS 'number_click' FROM origin_baidu")
			.append(" WHERE number_exhibit>10")
			.append(" AND number_click=0")
			.append(" AND company_id =").append(companyId).append(mainBusiness)
			.append(" AND DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(promotion_date)")
			.append("GROUP BY keyword_search LIMIT 10");
			List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(String.valueOf(sql));
			if(queryForList.size()>0){
				result.append("<br/>");
				result.append( "将一个月内展现量高于10次但没点击的词进行匹配调整（");
				List<Integer> list = new ArrayList<Integer>();
				Random r = new Random();
				while(list.size()<2){
					int num = r.nextInt(4);
					if(!list.contains(num)){
					   list.add(num);
					  } 
					}
				 String MatchingMode[] = new String[]{
						 "将“精确模式”调整为“精确包含”",
						 "将“精确包含”调整为“同义包含”",
						 "将”同义包含”调整为“核心包含”",
				 		 "将“核心包含”调整为“广泛"};
				for (Integer in : list) {
					result.append(MatchingMode[in]).append("；");
				}
				result.deleteCharAt(result.length()-1)
				.append("）或者将价格提成20%-30%，让这部分的关键词进行消费。这部分关键词有：")
				.append("");
				for (Map<String, Object> map : queryForList) {
					String keyword = (String) map.get("keyWord");
					 result.append("&nbsp;&nbsp;&nbsp;&nbsp;");
					result.append(keyword).append("<br/>");
				}
				result.delete(result.length()-5, result.length());
				return result.toString();
			}else{
				return result.append("</br>").toString();
			}
		}
		
		/*
		 * 定量规则第六条
		 * 
		 * 将一周内展现最低的关键词[从上传搜索词报告里提取展现量最低的10个关键词]进行匹配调整或者提高20%的出价，让这部分的关键词进行消费
		 */
		
		public String variableRule6(int companyId){
//			List<Map<String,Object>> lm = stratege14(companyId);
			String mainBusiness = this.getMajorBusiness(companyId);
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT keyword_search FROM origin_baidu WHERE company_id = "+companyId).append(mainBusiness);
			sql.append(" and promotion_date between '").append(getBeforeSimpleDate()).append("' and '").append(getNowSimpleDate()).append("'");
			sql.append(" and keyword_search not in('百度外链','直接访问','360外链') GROUP BY(`keyword_search`) order by number_exhibit LIMIT 10 ");
			List<Map<String,Object>> lm = jdbcTemplate.queryForList(sql.toString());
			StringBuffer result = new StringBuffer();
			if(lm!=null&&!lm.isEmpty()){
				result.append("将一周内展现最低的关键词进行匹配调整或者提高20%的出价，让这部分的关键词进行消费.一周内展现最低的关键词：").append("<br>");
				for(int i = 0 ; i< lm.size();i++){
					result.append("&nbsp;&nbsp;&nbsp;&nbsp;");
					result.append(lm.get(i).get("keyword_search")).append("<br/>");
				}
				result.delete(result.length()-5, result.length());
				return result.toString();
			}else{
				return "";
			}
			
		}
		
		
		/*
		 * 定量规则
		 */
		public String rationRule(int companyId, String industryId, String industryName){
			StringBuffer sb = new StringBuffer();
			//第一条
			sb.append(this.getSearchHotWordInfo(industryId)).append("</br>");
			//第二条
			sb.append(this.lowClickFor2(companyId)).append("</br>");
			//第三条
			sb.append(this.Advertisement03(companyId, industryId, industryName)).append("</br>");
			//第四条
			if("节能环保".equals(industryName)){
				sb.append(this.stratege37()).append("</br>");
			}if("物流".equals(industryName)){
				sb.append(this.stratege38()).append("</br>");
				sb.append("物流行业流量大，关键词建议设较精准的地域词，比如：xxx地方到或至xxx地方物流公司之类的词。").append("</br>");
			}if("租车".equals(industryName)){
				sb.append(this.strateget39()).append("</br>");
			}
			//sb.append(this.getSearchHotWordInfo(industryId));
			//第五条
			sb.append(this.lowConversionRateFor1()).append("</br>");
			//第六条
			sb.append(this.lowConversionRateFor2(companyId)).append("</br>");
			return sb.toString();
		}
		
		public String variableRule(int companyId, String industryId, String industryName){
			StringBuffer result = new StringBuffer();
			List<Integer> list = new ArrayList<Integer>();
			Random r = new Random();
			int temp = (int) (1+Math.random()*3);
			while(list.size()<temp){
				int num = r.nextInt(10)+1;
				if(!list.contains(num)){
				   list.add(num);
				  } 
			}
			for (Integer ranNum : list) {
				if(ranNum==1){
					result.append(this.variableRule1(companyId)).append("</br>");
				}
				if(ranNum==2){
					result.append(this.Advertisement02(companyId, industryId)).append("</br>");
				}
				if(ranNum==3){
					result.append(this.lowClickFor4()).append("</br>");
				}
				if(ranNum==4){
					result.append(this.Advertisement05(companyId, industryId)).append("</br>");
				}
				if(ranNum==5){
					result.append(this.Advertisement06(companyId, industryId)).append("</br>");
				}
				if(ranNum==6){
					result.append(this.variableRule6(companyId)).append("</br>");
				}
				if(ranNum==7){
					result.append(this.lowConversionRateFor3()).append("</br>");
				}
				if(ranNum==8){
					result.append(this.lowConversionRateFor4()).append("</br>");
				}
				if(ranNum==9){
					result.append(this.lowConversionRateFor5(companyId)).append("</br>");
				}
				if(ranNum==10){
					result.append(this.stratege36(industryId,companyId)).append("</br>");
				}
			}
			result.append(this.getStrategyFromDatabaseById(companyId)).append("</br>");
			return result.toString();
		}
		
		public String getMajorBusiness(Integer companyId){
		      StringBuffer sql = new StringBuffer();
		      sql.append("select major_business from company_major_business where company_id = ")
		        .append(companyId);
		      List<Map<String, Object>> list = jdbcTemplate.queryForList(String.valueOf(sql));
		      StringBuffer result = new StringBuffer();
		      result.append(" and origin_baidu.keyword_search like ");
		      if(!list.isEmpty()){
		      for(Map<String,Object> m : list){
		        String str = (String) m.get("major_business");
		        String[]  strArray = str.split(";");
		        for(String s:strArray){
		          result.append("'%").append(s).append("%'").append(" or ") ;
		        }
		        result.delete(result.length()-3, result.length());
		      }
		      return result.toString();
		      }
		      return "";
		    }
		
		public String getStrategyFromDatabaseById(int companyId){
			StringBuffer sql = new StringBuffer();
			StringBuffer result = new StringBuffer();
		      sql.append("SELECT company_name,strategy FROM strategy WHERE company_id =")
		      .append(companyId);
		      List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(String.valueOf(sql));
		      if(!queryForList.isEmpty()&&queryForList!=null){
		    	  for (Map<String, Object> map : queryForList) {
		    		  if(map.get("strategy")!=null){
		    			  result.append(map.get("strategy")).append("。").append("</br>");
		    		  }
		    	  }
		    	  return result.toString();
		      }else{
		    	  return "";
		      }
		}
		
}
